package com.atguigu.daijia.customer.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import com.alibaba.fastjson.JSON;
import com.atguigu.daijia.customer.mapper.CustomerInfoMapper;
import com.atguigu.daijia.customer.mapper.CustomerLoginLogMapper;
import com.atguigu.daijia.customer.service.CustomerInfoService;
import com.atguigu.daijia.model.entity.customer.CustomerInfo;
import com.atguigu.daijia.model.entity.customer.CustomerLoginLog;
import com.atguigu.daijia.model.form.customer.UpdateCustomerPhoneForm;
import com.atguigu.daijia.model.form.customer.UpdateWxPhoneForm;
import com.atguigu.daijia.model.vo.customer.CustomerLoginVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@Slf4j
@Service
@SuppressWarnings({"uncheck","rawtypes"})
@RequiredArgsConstructor
public class CustomerInfoServiceImpl extends ServiceImpl<CustomerInfoMapper, CustomerInfo> implements CustomerInfoService {


    private final WxMaService wxMaService;

    private final CustomerInfoMapper customerInfoMapper;

    private final CustomerLoginLogMapper customerLoginLogMapper;
    /**
     * 乘客小程序登录
     * @param code
     * @return
     */
    @Override
    public Long login(String code) {
        //1.获取code值
        String openid = null;
        try {
            WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(code);
            openid = sessionInfo.getOpenid();
        }catch (WxErrorException e){
            throw new RuntimeException(e);
        }

        //2.根据openid查询数据库，判断是否是第一次登录
        //如果openid不存在返回null，存在返回一条记录

        //todo 泛型类型要写匹配的类
        LambdaQueryWrapper<CustomerInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CustomerInfo::getWxOpenId,openid);
        //不是第一次登录,返回一条数据
        CustomerInfo customerInfo = customerInfoMapper.selectOne(wrapper);

        //3.如果第一次登录，添加信息到用户表
        if (customerInfo == null){
            //customerInfo = new CustomerInfo();
            //添加信息
            customerInfo = CustomerInfo.builder()
                    .nickname(String.valueOf(System.currentTimeMillis()))
                    .avatarUrl("https://oss.aliyuncs.com/aliyun_id_photo_bucket/default_handsome.jpg")
                    .wxOpenId(openid)
                    .build();
            customerInfoMapper.insert(customerInfo);
        }

        //4.记录登录日志信息
        CustomerLoginLog customerLoginLog = new CustomerLoginLog();
        customerLoginLog.setCustomerId(customerInfo.getId());
        customerLoginLog.setMsg("小程序登录");
        customerLoginLogMapper.insert(customerLoginLog);

        //返回用户id
        return customerInfo.getId();
    }

    /**
     * 获取客户登录信息
     * @param customerId
     * @return
     */
    @Override
    public CustomerLoginVo getCustomerInfo(Long customerId) {
        //1.根据用户id查询用户信息
        CustomerInfo customerInfo = customerInfoMapper.selectById(customerId);

        //2.封装到CustomerLoginVo
        CustomerLoginVo customerLoginVo = new CustomerLoginVo();
        BeanUtils.copyProperties(customerInfo,customerLoginVo);

        String phone = customerInfo.getPhone();
        boolean isBindPhone = StringUtils.hasText(phone);
        customerLoginVo.setIsBindPhone(isBindPhone);
        return customerLoginVo;
    }

    @SneakyThrows //使方法在遇到异常时，自动将异常转换为 java.lang.RuntimeException 并抛出，而无需显式地在方法中编写异常处理代码
    @Transactional(rollbackFor = {Exception.class})
    @Override
    public Boolean updateWxPhoneNumber(UpdateWxPhoneForm updateWxPhoneForm) {
        // 调用微信 API 获取用户的手机号
        WxMaPhoneNumberInfo phoneInfo = wxMaService.getUserService().getPhoneNoInfo(updateWxPhoneForm.getCode());
        String phoneNumber = phoneInfo.getPhoneNumber();
        log.info("phoneInfo:{}", JSON.toJSONString(phoneInfo));

        CustomerInfo customerInfo = new CustomerInfo();
        customerInfo.setId(updateWxPhoneForm.getCustomerId());
        customerInfo.setPhone(phoneNumber);
        //customerInfoMapper.updateById(customerInfo);
        return this.updateById(customerInfo);
    }
}
